"""
调起支付窗口
"""
import wx
import re
import os.path
from threading import Thread
from datetime import datetime
from wx.adv import Animation, AnimationCtrl

from src.api.order import create_order, order_status
from src.config import settings
from src.ui.transparent_stastictext import TransparentStaticText


class OrderDialog(wx.Dialog):
    def __init__(self, parent):
        super(OrderDialog, self).__init__(parent, title='用户充值')
        panel = wx.Panel(self)
        back = wx.StaticBitmap(panel, bitmap=wx.Bitmap(
            os.path.join(settings.assets_dir, 'bg.png')))
        info_tst = TransparentStaticText(self, label='请输入充值金额')
        info_tst.SetFont(wx.Font(12, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL,
                         wx.FONTWEIGHT_LIGHT, False, 'Microsoft YaHei'))
        info_tst.SetForegroundColour((255, 255, 255))
        info_tst.SetPosition((170, 60))
        self.order_amount = wx.TextCtrl(back, size=(100, 30), style=wx.TE_CENTRE)
        self.order_amount.SetFont(wx.Font(15, wx.MODERN, wx.NORMAL, wx.NORMAL, False, 'Consolas'))
        self.order_amount.SetPosition((180, 90))
        
        tip_tst = TransparentStaticText(self, label='*注意：如遇支付或费用问题，请联系微信：yongchunzha  ')
        tip_tst.SetFont(wx.Font(9, wx.FONTFAMILY_SCRIPT, wx.FONTSTYLE_SLANT,
                         wx.FONTWEIGHT_LIGHT, False, 'Microsoft YaHei'))
        tip_tst.SetForegroundColour((200, 200, 200))
        tip_tst.SetPosition((20, 270))
        
        start_button = wx.BitmapButton(back, bitmap=wx.Bitmap(
            os.path.join(settings.assets_dir, 'confirm.png')))
        start_button.SetPosition((160, 200))
        start_button.Bind(wx.EVT_BUTTON, self._create_order)

        panel.Fit()
        self.Fit()
        self.Centre()

    def _create_order(self, e):
        amount = self.order_amount.GetValue()
        if not re.match(r'^\d+\.?\d*$', str(amount)) or float(amount) < 0.99 or float(amount) > 1000:
            wx.MessageBox('订单金额必须大于1且小于1000！', '错误提示', wx.OK | wx.ICON_ERROR)
            return
        with PayDialog(self, amount) as pay_dlg:
            if pay_dlg.ShowModal() == wx.ID_CLOSE:
                wx.MessageBox('订单已取消!', '取消提示', wx.OK | wx.ICON_INFORMATION)


class PayDialog(wx.Dialog):
    def __init__(self, parent, amount):
        super(PayDialog, self).__init__(parent, title='支付页面')
        font_strong = wx.Font(18, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False,
                              'Microsoft YaHei')
        font_normal = wx.Font(12, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_LIGHT, False,
                              'Microsoft YaHei')
        self.amount = amount
        self.panel = wx.Panel(self)
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        title = wx.StaticText(self.panel, label='支付宝支付！')
        title.SetFont(font_strong)
        self.vbox.Add(title, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
        self.info = wx.StaticText(self.panel, label='请使用支付宝扫描下方二维码支付！')
        self.info.SetFont(font_normal)
        self.vbox.Add(self.info, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
        hline = wx.StaticLine(self.panel, style=wx.LI_HORIZONTAL)
        self.vbox.Add(hline, flag=wx.ALL | wx.EXPAND, border=10)
        self.animation = AnimationCtrl(self.panel, wx.ID_ANY, Animation(
            os.path.join(settings.assets_dir, 'load.gif')))
        self.animation.Play()
        self.vbox.Add(self.animation, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
        self.panel.SetSizer(self.vbox)
        self.panel.Fit()
        self.Fit()
        self.Centre()

        qr_thread = Thread(target=self.init_qrcode)
        qr_thread.setDaemon(True)
        qr_thread.start()
        self.timer = wx.Timer(self)
        self.start_time = None
        self.MAX_ORDER_TiME = 10 * 60  # 订单有效期：10分钟
        self.Bind(wx.EVT_TIMER, self.wait_pay, self.timer)

    def display_qrcode(self, qr_img):
        self.animation.Hide()
        width, height = qr_img.size
        bitmap = wx.Bitmap.FromBuffer(
            width, height, qr_img.convert('RGB').tobytes())
        qrcode = wx.StaticBitmap(self.panel, bitmap=bitmap)
        self.vbox.Add(qrcode, flag=wx.ALL | wx.ALIGN_CENTER, border=10)
        self.panel.Fit()
        self.Fit()

    def init_qrcode(self):
        status_code, data = create_order(self.amount)
        if status_code == 1000:
            self.order_no, qr_img = data['order_no'], data['qrcode']
            wx.CallAfter(self.display_qrcode, qr_img)
            self.start_time = datetime.now()
            wx.CallAfter(self.timer.Start, 1000)
        else:
            wx.MessageBox(str(data), '错误提示', wx.OK | wx.ICON_ERROR)
            self.Destroy()

    def wait_pay(self, e):  # 支付10分钟内有效
        status_code, data = order_status(self.order_no)
        if status_code == 1000 and data['paid']:
            self.timer.Stop()
            wx.MessageBox('充值成功！！', '成功提示', wx.OK | wx.ICON_INFORMATION)
            self.EndModal(wx.ID_OK)
            self.Destroy()
        elif status_code == 1000:
            used_seconds = (datetime.now() - self.start_time).total_seconds()
            if float(used_seconds) >= self.MAX_ORDER_TiME:
                self.timer.Stop()
                wx.MessageBox('订单超时！！', '错误提示', wx.OK | wx.ICON_ERROR)
                self.EndModal(wx.ID_ABORT)
                self.Destroy()
            minutes = int((self.MAX_ORDER_TiME - used_seconds) // 60)
            seconds = int((self.MAX_ORDER_TiME - used_seconds) % 60)
            wx.CallAfter(self.info.SetLabelText,
                         f'请在 {minutes} 分 {seconds} 秒内完成支付！')
        else:
            self.timer.Stop()
            wx.MessageBox(str(data), '错误提示', wx.OK | wx.ICON_ERROR)
            self.EndModal(wx.ID_ABORT)
            self.Destroy()


if __name__ == '__main__':
    app = wx.App()
    with OrderDialog(None) as dlg:
        dlg.ShowModal()
    app.MainLoop()
